package com.alibaba.ai;

import io.modelcontextprotocol.client.McpClient;
import io.modelcontextprotocol.client.McpSyncClient;
import io.modelcontextprotocol.client.transport.ServerParameters;
import io.modelcontextprotocol.client.transport.StdioClientTransport;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.mcp.SyncMcpToolCallbackProvider;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Bean;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.nio.file.Paths;
import java.time.Duration;

@SpringBootApplication
public class Application {

	public static void main(String[] args) {
        // 检查Node.js是否可用
        try {
            Process process = Runtime.getRuntime().exec("node --version");
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String version = reader.readLine();
            System.out.println("Node.js version: " + version);
        } catch (Exception e) {
            System.err.println("Node.js not found or not accessible");
            e.printStackTrace();
        }
		SpringApplication.run(Application.class, args);
	}

	@Bean
	public CommandLineRunner predefinedQuestions(ChatClient.Builder chatClientBuilder,
			McpSyncClient mcpClient, ConfigurableApplicationContext context) {

        return args -> {
            var chatClient = chatClientBuilder
                    .defaultToolCallbacks(new SyncMcpToolCallbackProvider(mcpClient))
                    .build();

            // 提取路径常量
            final String sourceFilePath = "C:\\Users\\86134\\IdeaProjects\\AlibabaAi\\spring-ai-alibaba-mcp-example\\spring-ai-alibaba-mcp-manual-example\\ai-mcp-fileserver\\target\\spring-ai-mcp-overview.txt";
            final String targetFilePath = "C:\\Users\\86134\\IdeaProjects\\AlibabaAi\\spring-ai-alibaba-mcp-example\\spring-ai-alibaba-mcp-manual-example\\ai-mcp-fileserver\\target\\summary.md";

            System.out.println("运行预定义问题并获取AI模型响应：\n");

            // 问题1 - 使用提取的路径
            String question1 = String.format("你能解释一下位于 %s 文件的内容吗？", sourceFilePath);
            System.out.println("问题1: " + question1);
            System.out.println("回答: " + chatClient.prompt(question1).call().content());

            // 问题2 - 使用提取的路径
            String question2 = String.format("请总结位于 %s 文件的内容，并以Markdown格式保存为 %s 文件？", sourceFilePath, targetFilePath);
            System.out.println("\n问题2: " + question2);
            System.out.println("回答: " +
                    chatClient.prompt(question2).call().content());

            context.close();

        };
	}

	@Bean(destroyMethod = "close")
	public McpSyncClient mcpClient() {

		// based on
		// https://github.com/modelcontextprotocol/servers/tree/main/src/filesystem
		// Windows 系统需要改为 npx.cmd
		var stdioParams = ServerParameters.builder("C:\\Program Files\\nodejs\\npx.cmd")
				.args("-y", "@modelcontextprotocol/server-filesystem", getDbPath())
				.build();

		var mcpClient = McpClient.sync(new StdioClientTransport(stdioParams))
				.requestTimeout(Duration.ofSeconds(120)).build();

		var init = mcpClient.initialize();

		System.out.println("MCP Initialized: " + init);

		return mcpClient;

	}

	private static String getDbPath() {

		// spring-ai-alibaba-examples/spring-ai-alibaba-mcp-example/spring-ai-alibaba-manual-mcp-example/ai-mcp-fileserver/target
		// windows use: spring-ai-alibaba-mcp-example/spring-ai-alibaba-manual-mcp-example/ai-mcp-fileserver/target
        String path = Paths.get(System.getProperty("user.dir"), "spring-ai-alibaba-mcp-example", "spring-ai-alibaba-mcp-manual-example", "ai-mcp-fileserver", "target").toString();
        System.out.println(path);
        return path;
	}

}
